﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractSrm;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs.SrmMsgs;
using HamcoWcs.Models.Devices;
using System;
using System.Linq;
using System.Threading;

namespace HamcoWcs.Service.Srm.SrmTaskParsers
{
    /// <summary>复机请求</summary>
    public class SrmParser_Recovery : SrmParserBase
    {
        public override EnumSrmRequest RequestType => EnumSrmRequest.RecoveryRequest;
        private readonly IBaseTaskService _baseTaskService;
        private readonly IMapper _mapper;

        public override void Deal(SrmDto srm, SrmPlc srmPlc)
        {
            _logger.AddWcsRunLog("Recovery", $"{srm.DeviceName}请求复机");

            try
            {
                if (srm.Enabled == 0 && srm.AnotherSrm.Enabled == 0)
                {

                    // [2023-10-19]都设宕是立即发送允许复机
                    var srmSendMsg = new SrmSendMsg(false)
                    {
                        Request = (ushort)EnumSrmSendMsg.AllowRecoveryRequest,
                    };
                    var deviceMsgQueueDto = new DeviceMsgQueueDto(srm, srmSendMsg);
                    _wcsDbContext.DeviceMsgQueues.Add(_mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto));
                    _wcsDbContext.SaveChanges();

                    return;
                }

                var k = $"{srm.Aisle.NodeName}RECOVERYFLAG";
                _config.SetConfigMsg(k, "1");
                Thread.Sleep(10);

                var plcNames = srmPlc.Srms.Values.Select(x => x.SrmName).ToList();
                var subTasks = _wcsDbContext.SubTasks
                    .Where(x => plcNames.Contains(x.PlcName))
                    .Where(x => x.TaskStatus == EnumSubTaskStatus.Ready.ToString())
                    .ToList();

                foreach (var subTask in subTasks)
                {
                    subTask.PlcName = srm.Aisle.NodeName;
                }

                _wcsDbContext.SaveChanges();
            }
            catch (Exception)
            {
                _logger.AddWcsRunLog("Recovery", $"{srm.DeviceName}设置复机请求状态失败");
            }
        }




        private readonly IBaseConfigService _config;
        public SrmParser_Recovery(IBaseTaskService baseTaskService, ILocationService locationService,
            WcsDbContext wcsDbContext, IMesCommunicateService mesCommunicateService, ILoggerService logger,
            IBaseConfigService config, IMapper mapper)
            : base(wcsDbContext, locationService, mesCommunicateService, logger)
        {
            _baseTaskService = baseTaskService;
            _config = config;
            _mapper = mapper;
        }

    }
}
